﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using HISModels.Entities;
using KeanuMvc.Reference;
using HISModels.ViewModel;

namespace HISRestServices.Services {

    [ServiceContract()]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class MedicalRecord : BaseServices, IDisposable {
        #region Field
        private HttpStatusCode statusCode = new HttpStatusCode();
        private string detailMessage = string.Empty;
        #endregion

        #region MedicalRecord

        [WebGet(UriTemplate = "medicalrecord/{patientid}")]
        public HttpResponseMessage<EpisodeDoctorRel> GetMedicalRecordById(int patientid) {
            HttpResponseMessage<EpisodeDoctorRel> returnValue = null;
            EpisodeDoctorRel medicalrecord = null;
            string userid = UserId;
            try {
                medicalrecord = (from b in AppContext.EpisodeDoctorRels
                                 join c in AppContext.Episodes on b.EpisodeId equals c.Id
                                 join d in AppContext.Doctors on b.DoctorId equals d.Id
                                 join e in AppContext.MemberEmployees on d.EmployeeId equals e.EmployeeId
                                 join f in AppContext.SysMemberships on e.MembershipId equals f.Id
                                 where c.PatientId == patientid && c.EpisodeStatus == 0 && f.UserId == userid
                                 select b).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<EpisodeDoctorRel>(statusCode);
                returnValue.Content = new ObjectContent<EpisodeDoctorRel>(medicalrecord);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }


            return returnValue;

        }

        [WebInvoke(Method = "POST", UriTemplate = "medicalrecord/paging/")]
        public HttpResponseMessage<DataTablesNet> GetMedicalRecordPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;
            string code = string.Empty;

            try {
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');
                code = data[0].Split('=')[1].NullSafeToString();

                var a = from b in AppContext.EpisodeDoctorRels
                        join c in AppContext.Episodes on b.EpisodeId equals c.Id
                        where c.EpisodeStatus == 0
                        select b;

                paging.iTotalRecords = a.Count();

                //a = a.Where(p => p.Assessment.Contains(code));

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "medicalrecord/")]
        public HttpResponseMessage<EpisodeDoctorRel> InsertMedicalRecord(EpisodeDoctorRel paramObject) {
            HttpResponseMessage<EpisodeDoctorRel> returnValue = null;
            string HeaderMessageKey = string.Empty;
            try {
                HeaderMessageKey = HISModels.Enums.ResponseMessage.DetailHeadesMessageKey;
                if (AppContext.EpisodeDoctorRels.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<EpisodeDoctorRel>(statusCode);
                returnValue.Content = new ObjectContent<EpisodeDoctorRel>(paramObject);
                returnValue.Headers.Add(HeaderMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "medicalrecord/")]
        public HttpResponseMessage<EpisodeDoctorRel> UpdateMedicalRecord(EpisodeDoctorRel paramObject) {
            HttpResponseMessage<EpisodeDoctorRel> returnValue = null;
            try {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<EpisodeDoctorRel>(statusCode);
                returnValue.Content = new ObjectContent<EpisodeDoctorRel>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebGet(UriTemplate = "medicalrecord/patient/{patientid}")]
        public HttpResponseMessage<List<EpisodeDoctorRel>> GetListMedicalRecord(int patientid) {
            HttpResponseMessage<List<EpisodeDoctorRel>> returnValue = null;
            List<EpisodeDoctorRel> listMedicalRecord = null;
            try {
                listMedicalRecord = (from b in AppContext.EpisodeDoctorRels
                                     join c in AppContext.Episodes on b.EpisodeId equals c.Id
                                     where c.PatientId == patientid
                                     select b).ToList();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<List<EpisodeDoctorRel>>(statusCode);
                returnValue.Content = new ObjectContent<List<EpisodeDoctorRel>>(listMedicalRecord);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        #endregion

        #region Vital Sign
        [WebInvoke(Method = "POST", UriTemplate = "vitalsign/paging/")]
        public HttpResponseMessage<DataTablesNet> GetVitalSignPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;
            int patientid = 0;

            try {
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');
                patientid = Convert.ToInt32(data[0].Split('=')[1]);

                var a = from b in AppContext.EpisodeDoctorRels
                        join c in AppContext.VitalSigns on b.Id equals c.EpisodeDoctorRelId
                        join d in AppContext.Episodes on b.EpisodeId equals d.Id
                        where d.PatientId == patientid && d.EpisodeStatus == 0
                        select c;

                paging.iTotalRecords = a.Count();

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "vitalsign/")]
        public HttpResponseMessage<VitalSign> InsertVitalSign(VitalSign paramObject) {
            HttpResponseMessage<VitalSign> returnValue = null;
            string HeaderMessageKey = string.Empty;
            try {
                HeaderMessageKey = HISModels.Enums.ResponseMessage.DetailHeadesMessageKey;
                if (AppContext.VitalSigns.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<VitalSign>(statusCode);
                returnValue.Content = new ObjectContent<VitalSign>(paramObject);
                returnValue.Headers.Add(HeaderMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "vitalsign/")]
        public HttpResponseMessage<VitalSign> UpdateVitalSign(VitalSign paramObject) {
            HttpResponseMessage<VitalSign> returnValue = null;
            try {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<VitalSign>(statusCode);
                returnValue.Content = new ObjectContent<VitalSign>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "vitalsign/")]
        public HttpResponseMessage<VitalSign> DeleteVitalSign(int id) {
            HttpResponseMessage<VitalSign> returnValue = null;
            VitalSign vitalsign = null;
            try {
                vitalsign = AppContext.VitalSigns.Where(d => d.Id == id).First();
                vitalsign.RecordStatus = 0;
                AppContext.Entry(vitalsign).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);

                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<VitalSign>(statusCode);
                returnValue.Content = new ObjectContent<VitalSign>(vitalsign);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }
        #endregion

        #region Physician Note

        [WebGet(UriTemplate = "physiciannote/{patientid}")]
        public HttpResponseMessage<List<PhysicianNote>> GetPhysicianNoteById(int patientid) {
            HttpResponseMessage<List<PhysicianNote>> returnValue = null;
            List<PhysicianNote> lstphynote = null;
            string userid = UserId;
            try {
                lstphynote = (from b in AppContext.EpisodeDoctorRels
                              join c in AppContext.Episodes on b.EpisodeId equals c.Id
                              join d in AppContext.PhysicianNotes on b.Id equals d.EpisodeDoctorRelId
                              where c.PatientId == patientid && c.EpisodeStatus == 0
                              select d).ToList();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<List<PhysicianNote>>(statusCode);
                returnValue.Content = new ObjectContent<List<PhysicianNote>>(lstphynote);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }


            return returnValue;

        }

        [WebInvoke(Method = "DELETE", UriTemplate = "physiciannote/")]
        public HttpResponseMessage<PhysicianNote> DeletePhysicianNote(int id) {
            HttpResponseMessage<PhysicianNote> returnValue = null;
            PhysicianNote phynote = null;
            try {
                phynote = AppContext.PhysicianNotes.Where(d => d.Id == id).First();
                phynote.RecordStatus = 0;
                AppContext.Entry(phynote).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);

                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<PhysicianNote>(statusCode);
                returnValue.Content = new ObjectContent<PhysicianNote>(phynote);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "physiciannote/")]
        public HttpResponseMessage<PhysicianNote> InsertPhysicianNote(PhysicianNote paramObject) {
            HttpResponseMessage<PhysicianNote> returnValue = null;
            string HeaderMessageKey = string.Empty;
            try {
                HeaderMessageKey = HISModels.Enums.ResponseMessage.DetailHeadesMessageKey;
                if (AppContext.PhysicianNotes.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<PhysicianNote>(statusCode);
                returnValue.Content = new ObjectContent<PhysicianNote>(paramObject);
                returnValue.Headers.Add(HeaderMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "physiciannote/")]
        public HttpResponseMessage<PhysicianNote> UpdatePhysicianNote(PhysicianNote paramObject) {
            HttpResponseMessage<PhysicianNote> returnValue = null;
            try {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<PhysicianNote>(statusCode);
                returnValue.Content = new ObjectContent<PhysicianNote>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }
        #endregion

        #region Physician Note Image

        [WebGet(UriTemplate = "physiciannote/image/{patientid}")]
        public HttpResponseMessage<PhysicianNoteImage> GetPhysicianNoteImageByPatId(int patientid) {
            HttpResponseMessage<PhysicianNoteImage> returnValue = null;
            PhysicianNoteImage phynoteimg = null;
            string userid = UserId;
            try {
                phynoteimg = (from b in AppContext.EpisodeDoctorRels
                              join c in AppContext.Episodes on b.EpisodeId equals c.Id
                              join d in AppContext.PhysicianNotes on b.Id equals d.EpisodeDoctorRelId
                              join e in AppContext.PhysicianNoteImages on d.Id equals e.PhysicianNoteId
                              where c.PatientId == patientid && c.EpisodeStatus == 0
                              select e).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<PhysicianNoteImage>(statusCode);
                returnValue.Content = new ObjectContent<PhysicianNoteImage>(phynoteimg);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }


            return returnValue;

        }

        [WebInvoke(Method = "DELETE", UriTemplate = "physiciannote/image/")]
        public HttpResponseMessage<PhysicianNoteImage> DeletePhysicianNoteImage(int id) {
            HttpResponseMessage<PhysicianNoteImage> returnValue = null;
            PhysicianNoteImage phynoteimg = null;
            try {
                phynoteimg = AppContext.PhysicianNoteImages.Where(d => d.Id == id).First();
                AppContext.Entry(phynoteimg).State = System.Data.EntityState.Deleted;
                AppContext.SaveChanges(UserId);

                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<PhysicianNoteImage>(statusCode);
                returnValue.Content = new ObjectContent<PhysicianNoteImage>(phynoteimg);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "physiciannote/image/")]
        public HttpResponseMessage<PhysicianNoteImage> InsertPhysicianNoteImage(PhysicianNoteImage paramObject) {
            HttpResponseMessage<PhysicianNoteImage> returnValue = null;
            string HeaderMessageKey = string.Empty;
            try {
                HeaderMessageKey = HISModels.Enums.ResponseMessage.DetailHeadesMessageKey;
                if (AppContext.PhysicianNoteImages.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<PhysicianNoteImage>(statusCode);
                returnValue.Content = new ObjectContent<PhysicianNoteImage>(paramObject);
                returnValue.Headers.Add(HeaderMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "physiciannote/image/")]
        public HttpResponseMessage<PhysicianNoteImage> UpdatePhysicianNoteImage(PhysicianNoteImage paramObject) {
            HttpResponseMessage<PhysicianNoteImage> returnValue = null;
            try {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<PhysicianNoteImage>(statusCode);
                returnValue.Content = new ObjectContent<PhysicianNoteImage>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        #endregion

        #region Habits
        [WebInvoke(Method = "POST", UriTemplate = "habits/paging/")]
        public HttpResponseMessage<DataTablesNet> GetHabitsPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;
            int patientid = 0;

            try {
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');
                patientid = Convert.ToInt32(data[0].Split('=')[1]);

                var a = from b in AppContext.Habits
                        join c in AppContext.EpisodeDoctorRels on b.EpisodeDoctorRelId equals c.Id
                        join d in AppContext.Episodes on c.EpisodeId equals d.Id
                        where d.PatientId == patientid && d.EpisodeStatus == 0
                        select b;

                paging.iTotalRecords = a.Count();

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.RecordTime);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "habits/")]
        public HttpResponseMessage<Habit> InsertHabits(Habit paramObject) {
            HttpResponseMessage<Habit> returnValue = null;
            string HeaderMessageKey = string.Empty;
            try {
                HeaderMessageKey = HISModels.Enums.ResponseMessage.DetailHeadesMessageKey;
                if (AppContext.Habits.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Habit>(statusCode);
                returnValue.Content = new ObjectContent<Habit>(paramObject);
                returnValue.Headers.Add(HeaderMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "habits/")]
        public HttpResponseMessage<Habit> UpdateHabits(Habit paramObject) {
            HttpResponseMessage<Habit> returnValue = null;
            try {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Habit>(statusCode);
                returnValue.Content = new ObjectContent<Habit>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }
        #endregion

        #region Medical Families
        [WebInvoke(Method = "POST", UriTemplate = "medicalfamilies/paging/")]
        public HttpResponseMessage<DataTablesNet> GetMedicalFamiliesPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;
            int patientid = 169;

            try {
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');
                patientid = Convert.ToInt32(data[0].Split('=')[1]);

                var a = from b in AppContext.EpisodeDoctorRels
                        join c in AppContext.MedicalFamilies on b.Id equals c.EpisodeDoctorRelId
                        join d in AppContext.Episodes on b.EpisodeId equals d.Id
                        where d.PatientId == patientid && d.EpisodeStatus == 0
                        select c;

                paging.iTotalRecords = a.Count();

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.RecordTime);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "medicalfamilies/")]
        public HttpResponseMessage<MedicalFamily> InsertMedicalFamilies(MedicalFamily paramObject) {
            HttpResponseMessage<MedicalFamily> returnValue = null;
            string HeaderMessageKey = string.Empty;
            try {
                HeaderMessageKey = HISModels.Enums.ResponseMessage.DetailHeadesMessageKey;
                if (AppContext.Habits.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<MedicalFamily>(statusCode);
                returnValue.Content = new ObjectContent<MedicalFamily>(paramObject);
                returnValue.Headers.Add(HeaderMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "medicalfamilies/")]
        public HttpResponseMessage<MedicalFamily> UpdateMedicalFamilies(MedicalFamily paramObject) {
            HttpResponseMessage<MedicalFamily> returnValue = null;
            try {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<MedicalFamily>(statusCode);
                returnValue.Content = new ObjectContent<MedicalFamily>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }
        #endregion

        #region Medical Histories
        [WebInvoke(Method = "POST", UriTemplate = "medicalhistories/paging/")]
        public HttpResponseMessage<DataTablesNet> GetMedicalHistoriesPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;
            int patientid = 0;

            try {
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');
                patientid = Convert.ToInt32(data[0].Split('=')[1]);

                var a = from b in AppContext.MedicalHistories
                        join c in AppContext.EpisodeDoctorRels on b.EpisodeDoctorRelId equals  c.Id 
                        join d in AppContext.Episodes on c.EpisodeId equals d.Id
                        where d.PatientId == patientid && d.EpisodeStatus == 0
                        select b;

                paging.iTotalRecords = a.Count();

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.RecordTime);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "medicalhistories/")]
        public HttpResponseMessage<MedicalHistory> InsertMedicalHistories(MedicalHistory paramObject) {
            HttpResponseMessage<MedicalHistory> returnValue = null;
            string HeaderMessageKey = string.Empty;
            try {
                HeaderMessageKey = HISModels.Enums.ResponseMessage.DetailHeadesMessageKey;
                if (AppContext.MedicalHistories.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<MedicalHistory>(statusCode);
                returnValue.Content = new ObjectContent<MedicalHistory>(paramObject);
                returnValue.Headers.Add(HeaderMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "medicalhistories/")]
        public HttpResponseMessage<MedicalHistory> UpdateMedicalHistories(MedicalHistory paramObject) {
            HttpResponseMessage<MedicalHistory> returnValue = null;
            try {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<MedicalHistory>(statusCode);
                returnValue.Content = new ObjectContent<MedicalHistory>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }
        #endregion

        #region Medical Occupation
        [WebInvoke(Method = "POST", UriTemplate = "medicaloccupation/paging/")]
        public HttpResponseMessage<DataTablesNet> GetMedicalOccupationPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;
            int patientid = 0;

            try {
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');
                patientid = Convert.ToInt32(data[0].Split('=')[1]);

                var a = from b in AppContext.MedicalOccupations
                        join c in AppContext.EpisodeDoctorRels on b.EpisodeDoctorRelId equals c.Id
                        join d in AppContext.Episodes on c.EpisodeId equals d.Id
                        where d.PatientId == patientid && d.EpisodeStatus == 0
                        select b;

                paging.iTotalRecords = a.Count();

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.RecordTime);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "medicaloccupation/")]
        public HttpResponseMessage<MedicalOccupation> InsertMedicalOccupation(MedicalOccupation paramObject) {
            HttpResponseMessage<MedicalOccupation> returnValue = null;
            string HeaderMessageKey = string.Empty;
            try {
                HeaderMessageKey = HISModels.Enums.ResponseMessage.DetailHeadesMessageKey;
                if (AppContext.MedicalHistories.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<MedicalOccupation>(statusCode);
                returnValue.Content = new ObjectContent<MedicalOccupation>(paramObject);
                returnValue.Headers.Add(HeaderMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "medicaloccupation/")]
        public HttpResponseMessage<MedicalOccupation> UpdateMedicalOccupation(MedicalOccupation paramObject) {
            HttpResponseMessage<MedicalOccupation> returnValue = null;
            try {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<MedicalOccupation>(statusCode);
                returnValue.Content = new ObjectContent<MedicalOccupation>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }
        #endregion

        #region Alergies
        [WebInvoke(Method = "POST", UriTemplate = "alergies/paging/")]
        public HttpResponseMessage<DataTablesNet> GetAlergiesPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;
            int patientid = 0;

            try {
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');
                patientid = Convert.ToInt32(data[0].Split('=')[1]);

                var a = from b in AppContext.EpisodeDoctorRels
                        join c in AppContext.Alergies on b.Id equals c.EpisodeDoctorRelId
                        join d in AppContext.Episodes on b.EpisodeId equals d.Id
                        where d.PatientId == patientid && d.EpisodeStatus == 0
                        select c;

                paging.iTotalRecords = a.Count();

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.RecordTime);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "alergies/")]
        public HttpResponseMessage<Alergy> InsertAlergies(Alergy paramObject) {
            HttpResponseMessage<Alergy> returnValue = null;
            string HeaderMessageKey = string.Empty;
            try {
                HeaderMessageKey = HISModels.Enums.ResponseMessage.DetailHeadesMessageKey;
                if (AppContext.Habits.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Alergy>(statusCode);
                returnValue.Content = new ObjectContent<Alergy>(paramObject);
                returnValue.Headers.Add(HeaderMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "alergies/")]
        public HttpResponseMessage<Alergy> UpdateAlergies(Alergy paramObject) {
            HttpResponseMessage<Alergy> returnValue = null;
            try {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Alergy>(statusCode);
                returnValue.Content = new ObjectContent<Alergy>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }
        #endregion

        #region Problem List
        [WebInvoke(Method = "POST", UriTemplate = "problemlist/paging/")]
        public HttpResponseMessage<DataTablesNet> GetProblemListPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;
            int patientid = 0;

            try {
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');
                patientid = Convert.ToInt32(data[0].Split('=')[1]);

                var a = from b in AppContext.EpisodeDoctorRels
                        join c in AppContext.ProblemLists on b.Id equals c.EpisodeDoctorRelId
                        join d in AppContext.Episodes on b.EpisodeId equals d.Id
                        where d.PatientId == patientid && d.EpisodeStatus == 0
                        select c;

                paging.iTotalRecords = a.Count();

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.RecordTime);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "problemlist/")]
        public HttpResponseMessage<ProblemList> InsertProblemList(ProblemList paramObject) {
            HttpResponseMessage<ProblemList> returnValue = null;
            string HeaderMessageKey = string.Empty;
            try {
                HeaderMessageKey = HISModels.Enums.ResponseMessage.DetailHeadesMessageKey;
                if (AppContext.Habits.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<ProblemList>(statusCode);
                returnValue.Content = new ObjectContent<ProblemList>(paramObject);
                returnValue.Headers.Add(HeaderMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "problemlist/")]
        public HttpResponseMessage<ProblemList> UpdateProblemList(ProblemList paramObject) {
            HttpResponseMessage<ProblemList> returnValue = null;
            try {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<ProblemList>(statusCode);
                returnValue.Content = new ObjectContent<ProblemList>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "problemlist/")]
        public HttpResponseMessage<ProblemList> DeleteProblemList(int id) {
            HttpResponseMessage<ProblemList> returnValue = null;
            ProblemList problemlist = null;
            try {
                problemlist = AppContext.ProblemLists.Where(d => d.Id == id).First();
                problemlist.RecordStatus = 0;
                AppContext.Entry(problemlist).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);

                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<ProblemList>(statusCode);
                returnValue.Content = new ObjectContent<ProblemList>(problemlist);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }
        #endregion

        #region Diet Record
        [WebGet(UriTemplate = "dietrecord/{patientid}")]
        public HttpResponseMessage<Diet> GetDietRecordByPatId(int patientid) {
            HttpResponseMessage<Diet> returnValue = null;
            Diet diet = null;
            try {
                diet = new Diet();
                var a = (from b in AppContext.Diets
                         join c in AppContext.MedicationPlans on b.MedicationPlanId equals c.Id
                         join d in AppContext.PhysicianNotes on c.PhysicianNoteId equals d.Id
                         join e in AppContext.EpisodeDoctorRels on d.EpisodeDoctorRelId equals e.Id
                         join f in AppContext.Episodes on e.EpisodeId equals f.Id
                         where f.PatientId == patientid && f.EpisodeStatus == 0
                         select b).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Diet>(statusCode);
                returnValue.Content = new ObjectContent<Diet>(diet);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }
        #endregion

        #region Radiology Record
        [WebGet(UriTemplate = "radiologyrecord/{patientid}")]
        public HttpResponseMessage<Radiology> GetRadiologyRecordByPatId(int patientid) {
            HttpResponseMessage<Radiology> returnValue = null;
            Radiology radiology = null;
            try {
                radiology = new Radiology();
                var a = (from b in AppContext.Radiologies
                         join c in AppContext.MedicationPlans on b.MedicationPlanId equals c.Id
                         join d in AppContext.PhysicianNotes on c.PhysicianNoteId equals d.Id
                         join e in AppContext.EpisodeDoctorRels on d.EpisodeDoctorRelId equals e.Id
                         join f in AppContext.Episodes on e.EpisodeId equals f.Id
                         where f.PatientId == patientid && f.EpisodeStatus == 0
                         select b).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Radiology>(statusCode);
                returnValue.Content = new ObjectContent<Radiology>(radiology);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }
        #endregion
    }
}